package com.infinitus.autocatlog.service;

import javax.servlet.http.HttpServletRequest;

public class RequestUtils {

	private static String filterXForwardedForIP(String ip) {
		if (ip == null || ip.trim().length() == 0) {
			return null;
		} else {
			String[] subIps = ip.split(",");

			if (subIps.length == 1) {
				return subIps[0];
			}

			for (int i = 0; i < subIps.length; i++) {
				String subIp = subIps[i];
				if (subIp == null || "null".equals(subIp) || subIp.trim().length() == 0) {
					continue;
				} else {
					subIp = subIp.trim();
					if (subIp.startsWith("192.168.") || subIp.startsWith("10.") || "127.0.0.1".equals(subIp)) {
						continue;
					} else if (subIp.startsWith("172.")) {
						String[] iptabs = subIp.split("\\.");
						int tab2 = Integer.parseInt(iptabs[1]);

						if (tab2 >= 16 && tab2 <= 31) {
							continue;
						} else {
							return subIp;
						}
					} else {
						return subIp;
					}
				}
			}
			return null;
		}
	}
	private static boolean isInnerIp(String ip) {
		return ip.startsWith("192.168.") || ip.startsWith("10.") || "127.0.0.1".equals(ip);
	}

	private static boolean invalidate(String ip) {
		return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "127.0.0.1".equalsIgnoreCase(ip)
		      || isInnerIp(ip);
	}

	public static String recordUserIp(HttpServletRequest request){
		StringBuilder sb =new StringBuilder();
		sb.append("&ipinfo=");
		sb.append("x-forwarded-for:").append(String.valueOf(request.getHeader("x-forwarded-for"))).append(";");
		sb.append("Proxy-Client-IP:").append(String.valueOf(request.getHeader("Proxy-Client-IP"))).append(";");
		sb.append("WL-Proxy-Client-IP:").append(String.valueOf(request.getHeader("WL-Proxy-Client-IP"))).append(";");
		sb.append("HTTP_CLIENT_IP:").append(String.valueOf(request.getHeader("HTTP_CLIENT_IP"))).append(";");		
		sb.append("HTTP_X_FORWARDED_FOR:").append(String.valueOf(request.getHeader("HTTP_X_FORWARDED_FOR"))).append(";");
		sb.append("X-Real-IP:").append(String.valueOf(request.getHeader("X-Real-IP"))).append(";");
		sb.append("RemoteAddr:").append(String.valueOf(request.getHeader("RemoteAddr")));
		
		return sb.toString();
	}
	
	public static String getRemoteIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");

		if (invalidate(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (invalidate(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (invalidate(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (invalidate(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (invalidate(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (invalidate(ip)) {
			ip = request.getRemoteAddr();
		}
		return filterXForwardedForIP(ip);
	}

}